local extension = Package:new("wu")
extension.extensionName = "klxf"
-- extension.game_modes_whitelist = { 'kl_heg_mode' }

Fk:loadTranslationTable {
  ["wu"] = "吴",
}

local U = require "packages/utility/utility"
local H = require "packages/klxf/util"

local sunquan = General(extension, "kl__sunquan", "wu", 4) --p.kingdom == player.kingdom
local kl__zhiheng = fk.CreateActiveSkill {
  name = "kl__zhiheng",
  anim_type = "control",
  prompt = "#kl__zhiheng-prompt",
  target_num = 1,
  card_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, player)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return
        #selected == 0 and
        Self.kingdom == target.kingdom and
        not target:isNude()
  end,
  on_use = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    local to_discard = room:getPlayerById(effect.tos[1])
    local cards = table.filter(to_discard:getCardIds("he"),
      function(id) return not to_discard:prohibitDiscard(Fk:getCardById(id)) end)

    local cid = room:askForCardsChosen(from, to_discard, 1, 999, { card_data = { { self.name, cards } } }, self.name)
    room:throwCard({ cid }, self.name, to_discard, from)

    local targets = table.filter(room.alive_players, function(p)
      return
          p.kingdom == from.kingdom
    end)
    local to_draw = room:askForChoosePlayers(from, table.map(targets, Util.IdMapper), 1, 1, "#kl__zhiheng-choose-draw",
      self.name, false)
    if #to_draw > 0 then
      room:getPlayerById(to_draw[1]):drawCards(#cid, self.name)
    end
  end
}
local kl__jiuyuan = fk.CreateTriggerSkill {
  name = "kl__jiuyuan",
  anim_type = "support",
  events = { fk.AfterCardsMove },
  can_trigger = function(self, event, target, player, data)
    if not player:isKongcheng() then return end
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand then
            return true
          end
        end
      end
    end
    return target == player
        and player:hasSkill(self)
        and not table.every(player.room:getOtherPlayers(player), function(p) return p.kingdom ~= player.kingdom end)
        and player.kingdom ~= "unknown"
        and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room:getOtherPlayers(player)) do
      if p:isAlive() and p.kingdom == player.kingdom then
        if room:askForSkillInvoke(p, self.name, data, "#kl__jiuyuan-ask::" .. player.id) then
          local cids = room:askForCard(p, 1, 1, false, self.name, true, ".|.|.|hand",
            "#kl__jiuyuan-give::" .. player.general)
          if cids and #cids > 0 then
            room:moveCardTo(cids, Player.Hand, player, fk.ReasonGive, self.name)
          end
          return true
        end
      end
    end
  end
}
sunquan:addSkill(kl__zhiheng)
sunquan:addSkill(kl__jiuyuan)
Fk:loadTranslationTable {
  ["kl__sunquan"] = "孙权",
  ["#kl__sunquan"] = "年轻的贤君",
  ["designer:kl__sunquan"] = "官方&抗绿先锋",

  ["kl__zhiheng"] = "制衡",
  [":kl__zhiheng"] = "出牌阶段限一次，你可观看一名与你势力相同的角色的手牌，弃置其至少一张牌，然后令一名与你势力相同的角色摸等量的牌。",
  ["#kl__zhiheng-prompt"] = "制衡：选择一名与你势力相同的角色",
  ["#kl__zhiheng-discard"] = "制衡：选择要弃置的牌",
  ["#kl__zhiheng-choose-draw"] = "制衡：令一名与你势力相同的角色摸等量张牌",

  ["kl__jiuyuan"] = "救援",
  [":kl__jiuyuan"] = "每回合限一次，当你失去所有手牌后，你可令所有与你势力相同的其他角色选择是否交给你一张手牌。",
  ["#kl__jiuyuan-ask"] = "救援：是否交给孙权一张手牌？", --bug
  ["#kl__jiuyuan-give"] = "救援：选择一张手牌交给孙权",

  ["$kl__zhiheng1"] = "不急不躁，稳谋应对。",
  ["$kl__zhiheng2"] = "制衡互牵，大局可安。",
  ["$kl__jiuyuan1"] = "你们真是朕的得力干将。",
  ["$kl__jiuyuan2"] = "有爱卿在，朕无烦忧。",
  ["~kl__sunquan"] = "锦绣江东，岂能失于我手……",
}

local zhangzhao = General(extension, "kl__zhangzhao", "wu", 3)
local kl__zhijian = fk.CreateActiveSkill {
  name = "kl__zhijian",
  anim_type = "support",
  prompt = "#kl__zhijian-prompt",
  card_num = 1,
  target_num = 1,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeEquip and
        Fk:currentRoom():getCardArea(to_select) == Card.PlayerHand
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and #selected_cards == 1
  end,
  on_use = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    local card = Fk:getCardById(effect.cards[1]) -- 确保 card 是卡牌对象
    local to = room:getPlayerById(effect.tos[1])
    from:showCards(card)
    room:useCard({
      from = to.id,
      tos = { { to.id } },
      card = card,
    })
    if not from.dead then
      room:drawCards(from, 1, self.name)
    end
  end
}
local kl__guzheng = fk.CreateTriggerSkill {
  name = "kl__guzheng",
  anim_type = "support",
  events = { fk.AfterCardsMove },
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryPhase) < 1 then
      local room = player.room
      local currentplayer = room.current
      if currentplayer and currentplayer.phase <= Player.Finish and currentplayer.phase >= Player.Start then
        local guzheng_pairs = {}
        for _, move in ipairs(data) do
          if move.moveReason == fk.ReasonDiscard and move.toArea == Card.DiscardPile and
              move.from ~= nil and
              move.proposer == move.from then
            local guzheng_value = guzheng_pairs[move.from] or {}
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                table.insert(guzheng_value, info.cardId)
              end
            end
            guzheng_pairs[move.from] = guzheng_value
          end
        end
        local guzheng_data, ids = { {}, {} }, {}
        for key, value in pairs(guzheng_pairs) do
          if not room:getPlayerById(key).dead and #value > 0 then
            ids = U.moveCardsHoldingAreaCheck(room, table.filter(value, function(id)
              return room:getCardArea(id) == Card.DiscardPile
            end))
            if #ids > 0 then
              table.insert(guzheng_data[1], key)
              table.insert(guzheng_data[2], ids)
            end
          end
        end
        if #guzheng_data[1] > 0 then
          self.cost_data = guzheng_data
          return true
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = self.cost_data[1]
    local card_pack = self.cost_data[2]
    if #targets == 1 then
      if room:askForSkillInvoke(player, self.name, nil, "#kl__guzheng-invoke::" .. targets[1]) then
        self.cost_data = { tos = targets, cards = card_pack[1] }
        return true
      end
    elseif #targets > 1 then
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#kl__guzheng-choose", self.name)
      if #tos > 0 then
        self.cost_data = { tos = { tos[1] }, cards = card_pack[table.indexOf(targets, tos[1])] }
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local toId = self.cost_data.tos[1]
    local toPlayer = room:getPlayerById(toId) -- 将 toId 转换为玩家对象
    room:doIndicate(player.id, { toId })
    local cards = self.cost_data.cards

    room:moveCardTo(cards, Card.Processing, nil, fk.ReasonJustMove, self.name, nil, true, player.id)

    cards = table.filter(cards, function(c) return room:getCardArea(c) == Card.Processing end)
    if not player.dead and not toPlayer.dead and #cards > 0 then
      local c = room:askForCardsChosen(toPlayer, toPlayer, 1, 1, { card_data = { { self.name, cards } } }, self.name,
        "Please choose cards")
      table.removeOne(cards, c[1])
      room:obtainCard(toPlayer, c, true, fk.ReasonPrey, player.id, self.name) --将选择的牌交给目标玩家。
    end
    if not player.dead and #cards > 0 then
      local c = room:askForCardsChosen(player, player, 1, 1, { card_data = { { self.name, cards } } }, self.name,
        "Please choose cards")                                              --让目标玩家从这些牌中选择一张。
      table.removeOne(cards, c[1])
      room:obtainCard(player, c, true, fk.ReasonPrey, player.id, self.name) --将选择的牌交给目标玩家。
    end

    cards = table.filter(cards, function(c) return room:getCardArea(c) == Card.Processing end)
    if #cards > 0 then
      room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name, nil, true, player.id)
    end
  end,
} --bug：1.同时机技能发动后就无法发动固政了，例如孙权制衡失去所有手牌发动救援后不会触发固政
zhangzhao:addSkill(kl__zhijian)
zhangzhao:addSkill(kl__guzheng)
Fk:loadTranslationTable {
  ["kl__zhangzhao"] = "张昭",
  ["#kl__zhangzhao"] = "功勳克举",
  ["designer:kl__zhangzhao"] = "官方&抗绿先锋",

  ["kl__zhijian"] = "直谏",
  [":kl__zhijian"] = "出牌阶段，你可展示手牌中的一张装备牌，令一名角色使用之，然后你摸一张牌。",
  ["#kl__zhijian-prompt"] = "直谏：选择一张装备牌和一名目标角色",
  ["kl__guzheng"] = "固政",
  [":kl__guzheng"] = "每阶段限一次，当一名角色弃置自己的牌后，你可令其与你各获得其中一张牌。",
  ["#kl__guzheng-invoke"] = "固政：是否发动固政？",
  ["#kl__guzheng-choose"] = "固政：选择一名目标角色",

  ["$kl__zhijian1"] = "陛下欲复昔日桓公之事乎？",
  ["$kl__zhijian2"] = "君者当御贤于后，安可校勇于猛兽！",
  ["$kl__guzheng1"] = "固国安邦，居当如是。",
  ["$kl__guzheng2"] = "今当稳固内政，以御外患。",
  ["~kl__zhangzhao"] = "哼哼！此皆老臣罪责，陛下岂会有过……",
}

local sunce = General(extension, "kl__sunce", "wu", 4)
local kl__jiang = fk.CreateTriggerSkill {
  name = "kl__jiang",
  anim_type = "drawcard",
  events = { fk.TargetSpecified, fk.TargetConfirmed },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
        (data.card.trueName == "slash" or data.card.name == "duel") and
        (event == fk.TargetConfirmed or data.firstTarget)
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}
sunce:addSkill(kl__jiang)
Fk:loadTranslationTable {
  ["kl__sunce"] = "孙策",
  ["#kl__sunce"] = "江东小霸王",
  ["designer:kl__sunce"] = "官方&江奕",

  ["kl__jiang"] = "激昂",
  [":kl__jiang"] = "当你使用【决斗】或【杀】指定目标后，或成为【决斗】或【杀】的目标后，你可以摸一张牌。",

  ["$kl__jiang1"] = "吾乃江东小霸王孙伯符！",
  ["$kl__jiang2"] = "江东子弟，何惧于天下！",
  ["~kl__sunce"] = "内事不决问张昭，外事不决问周瑜……",
}

local guyong = General(extension, "kl__guyong", "wu", 3)
local kl__shenxing = fk.CreateActiveSkill {
  name = "kl__shenxing",
  anim_type = "drawcard",
  prompt = "#kl__shenxing-active",
  card_num = 2,
  target_num = 0,
  can_use = Util.TrueFunc,
  card_filter = function(self, to_select, selected)
    return #selected < 2 and not Self:prohibitDiscard(Fk:getCardById(to_select))
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:throwCard(effect.cards, self.name, player, player)
    if not player.dead then
      player:drawCards(1, self.name)
    end
  end
}
local kl__bingyi = fk.CreateTriggerSkill {
  name = "kl__bingyi",
  anim_type = "defensive",
  events = { fk.AfterCardsMove },
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryPhase) < 1 and not player:isKongcheng() then
      local currentplayer = player.room.current
      if currentplayer and currentplayer.phase <= Player.Finish and currentplayer.phase >= Player.Start then
        for _, move in ipairs(data) do
          if move.from == player.id and move.moveReason == fk.ReasonDiscard then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                return true
              end
            end
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = player.player_cards[Player.Hand]
    player:showCards(cards)
    if #cards > 1 then
      for _, id in ipairs(cards) do
        if Fk:getCardById(id).color == Card.NoColor or Fk:getCardById(id).color ~= Fk:getCardById(cards[1]).color then
          return false
        end
      end
    end
    local tos = room:askForChoosePlayers(player, table.map(room:getOtherPlayers(player, false), Util.IdMapper), 1, #
      cards, "#kl__bingyi-choose:::" .. #cards, self.name, true)
    table.insert(tos, player.id)
    room:sortPlayersByAction(tos)
    for _, pid in ipairs(tos) do
      local p = room:getPlayerById(pid)
      if not p.dead then
        room:drawCards(p, 1, self.name)
      end
    end
  end,
}
guyong:addSkill(kl__shenxing)
guyong:addSkill(kl__bingyi)
Fk:loadTranslationTable {
  ["kl__guyong"] = "顾雍",
  ["#kl__guyong"] = "庙堂的玉磐",
  ["designer:kl__guyong"] = "官方&抗绿先锋",

  ["kl__shenxing"] = "慎行",
  [":kl__shenxing"] = "出牌阶段，你可弃置两张牌，然后摸一张牌。",
  ["#kl__shenxing-active"] = "发动 慎行，选择要弃置的两张牌",

  ["kl__bingyi"] = "秉壹",
  [":kl__bingyi"] = "每阶段限一次，当你因弃置而失去牌后，你可展示所有手牌。若颜色均相同，你令你与至多X名其他角色各摸一张牌（X为你的手牌数）。",
  ["#kl__bingyi-choose"] = "秉壹：你可令你与至多%arg名其他角色各摸一张牌",

  ["$kl__shenxing1"] = "审时度势，乃容万变。",
  ["$kl__shenxing2"] = "此需斟酌一二。",
  ["$kl__bingyi1"] = "公正无私，秉持如一。",
  ["$kl__bingyi2"] = "诸君看仔细了！",
  ["~kl__guyong"] = "病躯渐重，国事难安……",
}

local zhugejin = General(extension, "kl__zhugejin", "wu", 3)
local kl__hongyuan = fk.CreateTriggerSkill {
  name = "kl__hongyuan",
  anim_type = "defensive",
  events = { fk.AfterCardsMove },
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryPhase) < 1 and not player:isNude() then
      local currentplayer = player.room.current
      if currentplayer and currentplayer.phase <= Player.Finish and currentplayer.phase >= Player.Start then
        local x = 0
        for _, move in ipairs(data) do
          if move.to == player.id and move.toArea == Card.PlayerHand then
            x = x + #move.moveInfo
          end
        end
        return x > 1
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(room:getOtherPlayers(player, false), Util.IdMapper)
    for _ = 1, 2, 1 do
      if player.dead or player:isNude() then break end
      local tos, cardId = room:askForChooseCardAndPlayers(
        player,
        targets,
        1,
        1,
        ".",
        "#kl__hongyuan-give",
        self.name,
        true,
        true
      )
      if #tos > 0 then
        room:obtainCard(tos[1], cardId, false, fk.ReasonGive)
        targets = table.filter(targets, function(pid)
          return tos[1] ~= pid and not room:getPlayerById(pid).dead
        end)
        if #targets < 1 then break end
      else
        break
      end
    end
  end,
}
local kl__mingzhe = fk.CreateTriggerSkill {
  name = "kl__mingzhe",
  frequency = Skill.Compulsory,
  anim_type = "defensive",
  events = { fk.AfterCardsMove },
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player.phase ~= Player.Play then
      for _, move in ipairs(data) do
        if move.from == player.id and (move.to ~= player.id or (move.toArea ~= Card.PlayerHand and move.toArea ~= Card.PlayerEquip)) then
          for _, info in ipairs(move.moveInfo) do
            if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) and
                Fk:getCardById(info.cardId, true).color == Card.Red then
              return true
            end
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = {}
    for _, move in ipairs(data) do
      if move.from == player.id and (move.to ~= player.id or (move.toArea ~= Card.PlayerHand and move.toArea ~= Card.PlayerEquip)) then
        for _, info in ipairs(move.moveInfo) do
          if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) and
              Fk:getCardById(info.cardId, true).color == Card.Red and room:getCardArea(info.cardId) == Card.PlayerHand then
            table.insert(cards, info.cardId)
          end
        end
      end
    end
    if #cards > 0 then
      for _, p in ipairs(player.room.alive_players) do
        local to_show = table.filter(cards, function(id)
          return room:getCardOwner(id) == p
        end)
        if #to_show > 0 then
          p:showCards(to_show)
        end
      end
    end
    player:drawCards(1, self.name)
  end,
}
zhugejin:addSkill(kl__hongyuan)
zhugejin:addSkill(kl__mingzhe)
Fk:loadTranslationTable {
  ["kl__zhugejin"] = "诸葛瑾",
  ["#kl__zhugejin"] = "联盟的维系者",
  ["designer:kl__zhugejin"] = "官方&抗绿先锋",

  ["kl__hongyuan"] = "弘援",
  [":kl__hongyuan"] = "每阶段限一次，当你一次性获得至少两张牌后，你可将至多两张牌交给等量的角色。",
  ["kl__mingzhe"] = "明哲",
  [":kl__mingzhe"] = "锁定技，当你于出牌阶段外失去红色牌后，展示之，然后你摸一张牌。",
  ["#kl__hongyuan-give"] = "弘援：你可选择一张牌交给一名角色",

  ["$kl__hongyuan1"] = "诸将莫慌，粮草已到。",
  ["$kl__hongyuan2"] = "自舍其身，施于天下。",
  ["$kl__mingzhe1"] = "明以洞察，哲以保身。",
  ["$kl__mingzhe2"] = "塞翁失马，焉知非福？",
  ["~kl__zhugejin"] = "联盟若能得以维系，吾……无他愿矣……",
}

local buzhi = General(extension, "kl__buzhi", "wu", 3)
local kl__hongde = fk.CreateTriggerSkill {
  name = "kl__hongde",
  anim_type = "drawcard",
  events = { fk.AfterCardsMove },
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      for _, move in ipairs(data) do
        if #move.moveInfo > 1 and ((move.from == player.id and move.to ~= player.id) or
              (move.to == player.id and move.toArea == Card.PlayerHand)) then
          return true
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getAlivePlayers(), Util.IdMapper), 1, 1,
      "#kl__hongde-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:getPlayerById(self.cost_data):drawCards(1, self.name)
  end,
}
local kl__dingpan = fk.CreateActiveSkill {
  name = "kl__dingpan",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  prompt = "#kl__dingpan",
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and #Fk:currentRoom():getPlayerById(to_select):getCardIds("e") > 0 and
        Fk:currentRoom():getPlayerById(to_select):getMark("_kl__dingpan-phase") == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:setPlayerMark(target, "_kl__dingpan-phase", 1)
    target:drawCards(1, self.name)
    local choice = room:askForChoice(target, { "kl__dingpan_discard:" .. player.id, "kl__dingpan_damage:" .. player.id },
      self.name)
    if choice[10] == "i" then
      local id = room:askForCardChosen(player, target, "e", self.name)
      room:throwCard({ id }, self.name, target, player)
    else
      room:moveCardTo(target:getCardIds("e"), Card.PlayerHand, target, fk.ReasonJustMove, self.name, nil, true, target
        .id)
      if not target.dead then
        room:damage {
          from = player,
          to = target,
          damage = 1,
          skillName = self.name,
        }
      end
    end
  end,
}
buzhi:addSkill(kl__hongde)
buzhi:addSkill(kl__dingpan)
Fk:loadTranslationTable {
  ["kl__buzhi"] = "步骘",
  ["#kl__buzhi"] = "积跬靖边",
  ["designer:kl__buzhi"] = "官方&抗绿先锋",

  ["kl__hongde"] = "弘德",
  [":kl__hongde"] = "当你一次获得或失去至少两张牌后，你可以令一名角色摸一张牌。",
  ["kl__dingpan"] = "定叛",
  [":kl__dingpan"] = "出牌阶段每名角色限一次，你可令一名装备区里有牌的角色摸一张牌，然后其选择一项：1.你弃置其装备区里的一张牌；" ..
      "2.获得其装备区里的所有牌，你对其造成1点伤害。",
  ["#kl__hongde-choose"] = "弘德：你可以令一名角色摸一张牌",
  ["#kl__dingpan"] = "定叛：令一名装备区里有牌的角色摸一张牌，然后其选择弃置装备或收回装备并受到你造成的伤害",
  ["kl__dingpan_discard"] = "%src弃置你装备区里的一张牌",
  ["kl__dingpan_damage"] = "收回所有装备，%src对你造成1点伤害",

  ["$kl__hongde1"] = "江南重义，东吴尚德。",
  ["$kl__hongde2"] = "德无单行，福必双至。",
  ["$kl__dingpan1"] = "从孙者生，从刘者死！",
  ["$kl__dingpan2"] = "多行不义必自毙！",
  ["~kl__buzhi"] = "交州已定，主公尽可放心。",
}

local lvmeng = General(extension, "kl__lvmeng", "wu", 4)
local kl__keji = fk.CreateTriggerSkill {
  name = "kl__keji",
  anim_type = "defensive",
  events = { fk.EventPhaseStart },
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Discard and
        #player:getTableMark("@kl__keji-turn") < 5
  end,
  on_use = function(self, event, target, player, data)
    player.room:addPlayerMark(player, MarkEnum.AddMaxCardsInTurn, 4 - #player:getTableMark("@kl__keji-turn"))
  end,

  refresh_events = { fk.CardUsing },
  can_refresh = function(self, event, target, player, data)
    return player == target and player:hasSkill(self, true) and player.phase ~= Player.NotActive
        and data.card.suit ~= Card.NoSuit and #player:getTableMark("@kl__keji-turn") < 4
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:addTableMarkIfNeed(player, "@kl__keji-turn", data.card:getSuitString(true))
  end,

}
local kl__botu = fk.CreateTriggerSkill {
  name = "kl__botu",
  events = { fk.TurnEnd },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
        and (#player:getTableMark("@kl__botu-turn") == 4 or #player:getTableMark("@kl__botu-turn") < 2)
  end,
  on_use = function(self, event, target, player, data)
    if #player:getTableMark("@kl__botu-turn") == 4 then
      player:gainAnExtraTurn()
    elseif #player:getTableMark("@kl__botu-turn") < 2 then
      player:drawCards(1, self.name)
    end
  end,

  refresh_events = { fk.CardUsing },
  can_refresh = function(self, event, target, player, data)
    return player == target and player:hasSkill(self, true) and player.phase ~= Player.NotActive
        and data.card.suit ~= Card.NoSuit and #player:getTableMark("@kl__botu-turn") < 4
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:addTableMarkIfNeed(player, "@kl__botu-turn", data.card:getSuitString(true))
  end,
}
lvmeng:addSkill(kl__keji)
lvmeng:addSkill(kl__botu)
Fk:loadTranslationTable {
  ["kl__lvmeng"] = "吕蒙",
  ["#kl__lvmeng"] = "白衣渡江",
  ["designer:kl__lvmeng"] = "官方&抗绿先锋",

  ["kl__keji"] = "克己",
  [":kl__keji"] = "锁定技，弃牌阶段开始时，本回合你的手牌上限+X（X为本回合你未使用过的花色数）。",
  ["kl__botu"] = "博图",
  [":kl__botu"] = "回合结束时，若本回合你使用过的花色数：等于4，你可执行一个额外回合；小于2，你可摸一张牌。",
  ["@kl__botu-turn"] = "博图",
  ["@kl__keji-turn"] = "克己",

  ["$kl__keji1"] = "哼，笑到最后的，才是赢家。",
  ["$kl__keji2"] = "静观其变，相机而动。",
  ["$kl__botu1"] = "今日起兵，渡江攻敌！",
  ["$kl__botu2"] = "时机已到，全军出击！。",
  ["~kl__lvmeng"] = "被看穿了吗……",
}

local huanggai = General(extension, "kl__huanggai", "wu", 4)
local kl__zhaxiang = fk.CreateActiveSkill {
  name = "kl__zhaxiang",
  anim_type = "control",
  prompt = "#kl__zhaxiang-prompt",
  target_num = 1,
  card_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, player)
    return #selected == 0
  end,
  on_use = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.tos[1])
    to:drawCards(1, self.name)
    if not to.dead and not from.dead then
      room:useVirtualCard("fire_attack", nil, from, to, self.name, true)
    end
  end
}
local kl__kurou = fk.CreateTriggerSkill {
  name = "kl__kurou",
  anim_type = "masochism",
  events = { fk.Damaged },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
        not data.from
        .dead --and data.from and not data.from.dead and not data.from:isNude()
  end,
  on_trigger = function(self, event, target, player, data)
    self.cancel_cost = false
    for i = 1, data.damage do
      if i > 1 and (self.cancel_cost or not player:hasSkill(self)) then break end
      self:doCost(event, target, player, data)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local current = player.room.current
    room:doIndicate(player.id, { data.from.id })
    data.from:drawCards(2, self.name)
    if current == data.from then
      room:addPlayerMark(current, MarkEnum.SlashResidue .. "-turn", 1)
    end
  end
}
huanggai:addSkill(kl__kurou)
huanggai:addSkill(kl__zhaxiang)
Fk:loadTranslationTable {
  ["kl__huanggai"] = "黄盖",
  ["#kl__huanggai"] = "轻身为国",
  ["designer:kl__huanggai"] = "官方&3d吧",

  ["kl__kurou"] = "苦肉",
  [":kl__kurou"] = "当你受到1点伤害后，你可令当前回合角色摸两张牌，其本回合使用【杀】的次数上限+1。",
  ["kl__zhaxiang"] = "诈降",
  [":kl__zhaxiang"] = "出牌阶段限一次，你可令一名角色摸一张牌，视为对其使用一张【火攻】。",
  ["#kl__zhaxiang-prompt"] = "可令一名角色摸一张牌，视为对其使用一张【火攻】。",

  ["$kl__kurou1"] = "我这把老骨头，不算什么！",
  ["$kl__kurou2"] = "为成大业，死不足惜！",
  ["$kl__zhaxiang1"] = "铁锁连舟而行，东吴水师可破！",
  ["$kl__zhaxiang2"] = "两军阵前，不斩降将！",
  ["~kl__huanggai"] = "盖，有负公瑾重托……",
}

local zhoutai = General(extension, "kl__zhoutai", "wu", 4)
local kl__buqu = fk.CreateTriggerSkill {
  name = "kl__buqu",
  anim_type = "defensive",
  events = { fk.AskForPeaches },
  frequency = Skill.Compulsory,
  derived_piles = "kl__buqu_scar",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.dying
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local scar_id = room:getNCards(1)[1]
    local scar = Fk:getCardById(scar_id)
    player:addToPile("kl__buqu_scar", scar_id, true, self.name)
    if player.dead or not table.contains(player:getPile("kl__buqu_scar"), scar_id) then return false end
    local success = true
    for _, id in pairs(player:getPile("kl__buqu_scar")) do
      if id ~= scar_id then
        local card = Fk:getCardById(id)
        if (card.number == scar.number) then
          success = false
          break
        end
      end
    end
    if success then
      room:recover({
        who = player,
        num = 1 - player.hp,
        recoverBy = player,
        skillName = self.name
      })
    else
      room:throwCard(scar:getEffectiveId(), self.name, player)
    end
  end,
}
local kl__fenji = fk.CreateViewAsSkill {
  name = "kl__fenji",
  anim_type = "defensive",
  pattern = ".|.|.|.|.|basic",
  prompt = function()
    return "#kl__fenji-card"
  end,
  interaction = function()
    local all_names = U.getAllCardNames("b")
    local names = U.getViewAsCardNames(Self, "kl__fenji", all_names, {}, Self:getTableMark("kl__fenji-turn"))
    if #names == 0 then return false end
    return U.CardNameBox { choices = names, all_choices = all_names }
  end,
  card_filter = Util.FalseFunc,
  before_use = function(self, player, use)
    local room = player.room
    room:addTableMark(player, "kl__fenji-turn", use.card.trueName)
    room:loseHp(player, 1, self.name)
  end,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:setMark(self.name, cards[1])
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return player.hp > 0
  end,
  enabled_at_response = function(self, player, response)
    return player.hp > 0 and not response
  end,
} --bug:需要响应牌时按钮是灰色的
zhoutai:addSkill(kl__buqu)
zhoutai:addSkill(kl__fenji)
Fk:loadTranslationTable {
  ['kl__zhoutai'] = '周泰',
  ["#kl__zhoutai"] = "历战之躯",
  ["designer:kl__zhoutai"] = "官方&抗绿先锋",

  ["kl__buqu"] = "不屈",
  [":kl__buqu"] = "锁定技，当你处于濒死状态时，你将牌堆顶的一张牌置于你的武将牌上，称为“创”，若此牌的点数与已有的“创”点数：均不同，则你将体力回复至1点；存在相同，将此牌置入弃牌堆。",
  ["kl__fenji"] = "奋激",
  [":kl__fenji"] = "每回合每牌名限一次，当你需要使用基本牌时，你可失去1点体力，视为使用之。",
  ["#kl__fenji-card"] = "每回合每牌名限一次，你可失去1点体力，视为使用或打出任意基本牌",
  ["kl__buqu_scar"] = "创",

  ["$kl__buqu1"] = "战如熊虎，不惜躯命！",
  ["$kl__buqu2"] = "哼，这点小伤算什么！",
  ["$kl__fenji1"] = "百战之身，奋勇驱前！",
  ["$kl__fenji2"] = "两肋插刀，愿赴此躯！",
  ["~kl__zhoutai"] = "敌众我寡，无力回天……",
}

local xusheng = General(extension, "kl__xusheng", "wu", 4)
local kl__pojun = fk.CreateTriggerSkill {
  name = "kl__pojun",
  anim_type = "offensive",
  events = { fk.TargetSpecified, fk.DamageCaused },
  can_trigger = function(self, event, target, player, data)
    local pojunCheck = function()
      local useEvent = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard, true)
      if useEvent then
        local use = useEvent.data[1]
        return (use.extra_data or {}).steam__choujue_pojun == player.id
      end
      return false
    end
    if target == player and data.card and
        ((player:hasSkill(self) and data.card.trueName == "slash") or (data.card.name == "duel" and pojunCheck())) then
      if event == fk.TargetSpecified then
        local to = player.room:getPlayerById(data.to)
        return not to.dead and to.hp > 0 and not to:isNude()
      elseif event == fk.DamageCaused then
        return player:getHandcardNum() >= data.to:getHandcardNum() and
            #player:getCardIds(Player.Equip) >= #data.to:getCardIds(Player.Equip)
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.TargetSpecified then
      if (data.card.name == "duel") or player.room:askForSkillInvoke(player, self.name, nil, "#kl__pojun-invoke::" .. data.to) then
        self.cost_data = { tos = { data.to } }
        return true
      end
    else
      self.cost_data = { tos = { data.to.id } }
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetSpecified then
      local to = room:getPlayerById(data.to)
      local cards = room:askForCardsChosen(player, to, 1, to.hp, "he", self.name)
      to:addToPile("$kl__pojun", cards, false, self.name)
    else
      data.damage = data.damage + 1
    end
  end,
}
local kl__pojun_delay = fk.CreateTriggerSkill {
  name = "#kl__pojun_delay",
  mute = true,
  events = { fk.TurnEnd },
  can_trigger = function(self, event, target, player, data)
    return #player:getPile("$kl__pojun") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player.room:moveCardTo(player:getPile("$kl__pojun"), Player.Hand, player, fk.ReasonPrey, "kl__pojun")
  end,
}
kl__pojun:addRelatedSkill(kl__pojun_delay)
xusheng:addSkill(kl__pojun)
Fk:loadTranslationTable {
  ["kl__xusheng"] = "徐盛",
  ["#kl__xusheng"] = "江东铁壁",
  ["designer:kl__xushen"] = "官方",

  ["kl__pojun"] = "破军",
  ["#kl__pojun_delay"] = "破军",
  [":kl__pojun"] = "①当你使用【杀】指定一个目标后，你可以将其至多X张牌扣置于该角色的武将牌旁（X为其体力值）；若如此做，当前回合结束时，该角色获得这些牌。②当你使用【杀】对手牌数与装备区里的牌数均不大于你的角色造成伤害时，此伤害+1。",
  ["#kl__pojun-invoke"] = "破军：你可以扣置 %dest 至多其体力值张牌直到回合结束",
  ["$kl__pojun"] = "破军",

  ["$kl__pojun1"] = "犯大吴疆土者，盛必击而破之！",
  ["$kl__pojun2"] = "若敢来犯，必叫你大败而归！",
  ["~kl__xusheng"] = "盛只恨，不能再为主公，破敌致胜了。",
}

-- local kl__panzhangmazhong = General(extension, "kl__panzhangmazhong", "wu", 4)
-- local kl__qianglue = fk.CreateActiveSkill {
--   name = "kl__qianglue",
--   anim_type = "offensive",
--   card_num = 0,
--   target_num = 1,
--   can_use = function(self, player)
--     return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
--   end,
--   card_filter = Util.FalseFunc,
--   target_filter = function(self, to_select, selected, selected_cards)
--     return #selected == 0 and to_select ~= Self.id and Self:canPindian(Fk:currentRoom():getPlayerById(to_select))
--   end,
--   on_use = function(self, room, effect)
--     local player = room:getPlayerById(effect.from)
--     local target = room:getPlayerById(effect.tos[1])
--     local pindian = player:pindian({ target }, self.name)
--     if pindian.results[target.id].winner == player then
--       local card = room:askForCardChosen(player, target, "he", self.name)
--       room:obtainCard(player, card, false, fk.ReasonPrey)
--     end
--   end,
-- }
-- local kl__anjianp = fk.CreateTriggerSkill {
--   name = "kl__anjianp",
--   anim_type = "offensive",
--   events = { fk.TargetSpecified },
--   can_trigger = function(self, event, target, player, data)
--     return target == player and player:hasSkill(self) and data.card.trueName == "slash"
--         and not player.room:getPlayerById(data.to):inMyAttackRange(player)
--   end,
--   on_use = function(self, event, target, player, data)
--     local room = player.room
--     if room:askForChoice(player, { "disresponsive", "kl__anjianp_damage" }, self.name, "#kl__anjianp-choice:" .. data.to) == "disresponsive" then
--       data.disresponsive = true
--     else
--       data.additionalDamage = (data.additionalDamage or 0) + 1
--     end
--   end,
-- }
-- kl__panzhangmazhong:addSkill(kl__anjianp) --没写完
-- kl__panzhangmazhong:addSkill(kl__qianglue)
-- Fk:loadTranslationTable {
--   ["kl__panzhangmazhong"] = "潘璋马忠",
--   ["#kl__panzhangmazhong"] = "擒龙伏虎",
--   ["designer:kl__panzhangmazhong"] = "官方&抗绿先锋",

--   ["kl__qianglue"] = "强掠",
--   [":kl__qianglue"] = "出牌阶段限一次或当你使用【杀】造成伤害后，你可拼点。若你赢，你获得对方一张牌。",
--   ["kl__anjianp"] = "暗箭",
--   [":kl__anjianp"] = "当你使用【杀】指定目标后，若你不在其攻击范围内，你可令此【杀】不能被其响应或对其造成的伤害+1。",
--   ["#kl__anjianp-choice"] = "暗箭：令 %src 不能响应此【杀】或受到此【杀】伤害+1",
--   ["kl__anjianp_damage"] = "伤害+1",

--   ["$kl__qianglue1"] = "这刀岂是你配用的？",
--   ["$kl__qianglue2"] = "夺敌兵刃，如断其臂！",
--   ["$kl__anjianp1"] = "看我一箭索命！",
--   ["$kl__anjianp2"] = "明枪易躲，暗箭难防！",
--   ["~kl__panzhangmazhong"] = "怎么可能，我明明亲手将你……",
-- }

local zhuran = General(extension, "kl__zhuran", "wu", 4)
-- local kl__danshou = fk.CreateTriggerSkill {
--   name = "kl__danshou",
--   anim_type = "control",
--   mute = true,
--   events = { fk.Damage },
--   on_use = function(self, event, target, player, data)
--     local room = player.room
--     player:broadcastSkillInvoke("danshou")
--     room:notifySkillInvoked(player, self.name)
--     player:drawCards(2, self.name)
--     room.logic:breakTurn()
--   end,
-- }
local kl__danshou = fk.CreateTriggerSkill {
  name = "kl__danshou",
  events = { fk.TargetConfirmed },
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target == player and data.from ~= player.id and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 then
      local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e)
        local use = e.data[1]
        return table.contains(TargetGroup:getRealTargets(use.tos), player.id)
      end, Player.HistoryTurn)
      self.cost_data = #events
      return true
    end
  end,
  on_cost = function(self, event, target, player, data)
    local n = player:getHandcardNum() - self.cost_data
    if n > 0 then
      local cards = player.room:askForDiscard(player, n, n, false, self.name, true, ".",
        "#kl__danshou-damage::" .. data.from .. ":" .. n, true)
      if #cards == n then
        self.cost_data = { n, cards }
        return true
      end
    else
      self.cost_data = { n }
      return player.room:askForSkillInvoke(player, self.name, nil, "#kl__danshou:::" .. -n)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if self.cost_data[1] > 0 then
      local to = room:getPlayerById(data.from)
      room:doIndicate(player.id, { data.from })
      room:throwCard(self.cost_data[2], self.name, player, player)
      if not to.dead then
        room:damage {
          from = player,
          to = to,
          damage = 1,
          skillName = self.name,
        }
      end
    else
      player:drawCards(-self.cost_data[1], self.name)
    end
  end,
}
zhuran:addSkill(kl__danshou)
Fk:loadTranslationTable {
  ["kl__zhuran"] = "朱然",
  ["#kl__zhuran"] = "胆略无双",
  ["designer:kl__zhuran"] = "教父&二四",

  ["kl__danshou"] = "胆守",
  [":kl__danshou"] = "每回合限一次，当你成为其他角色使用牌的目标后，你可将手牌调整至X张，若你因此法失去牌，你对其造成1点伤害（X为你本回合成为过牌目标的次数）。",

  ["#kl__danshou-damage"] = "胆守：你可以弃置 %arg 张牌，对 %dest 造成1点伤害",
  ["#kl__danshou"] = "胆守：你可以摸 %arg 张牌",
  ["$kl__danshou1"] = "此城危难，我必当竭尽全力！",
  ["$kl__danshou2"] = "大丈夫屈伸有道，不在一时胜负。",
  ["~kl__zhuran"] = "何人竟有如此之胆！？",
}

local luxun = General(extension, "kl__luxun", "wu", 3)
local kl__qianxun = fk.CreateTriggerSkill {
  name = "kl__qianxun",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = { fk.AfterCardsMove },
  can_trigger = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then
      if not player:hasSkill(self) then return end
      if player:hasSkill(self) then
        for _, move in ipairs(data) do
          if move.from == player.id and move.moveReason ~= fk.ReasonUse then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                return true
              end
            end
          end
        end
      end
    else
      if not player:hasSkill(self) or player:getMark("kl__qianxun2-turn") > 0 or not player.chained or target ~= player then return end
      if data.damageType == fk.NormalDamage then
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local x = player:getHandcardNum() - player:getMaxCards()
    if x >= 0 then
      return room:addPlayerMark(player, MarkEnum.AddMaxCards, 1)
    else
      room:drawCards(player, 1, self.name)
      return room:addPlayerMark(player, MarkEnum.MinusMaxCards, 1)
    end
  end
}
local kl__duoshi = fk.CreateViewAsSkill {
  name = "kl__duoshi",
  anim_type = "offensive",
  pattern = ".",
  prompt = "#kl__duoshi",
  interaction = function(self, player)
    if player:isNude() then
      local all_names = { "await_exhausted", }
      local names = U.getViewAsCardNames(player, "kl__duoshi", all_names, nil)
      if #names == 0 then return end
      return U.CardNameBox {
        choices = names,
        all_choices = all_names,
        -- default_choice = "kl__duoshi"
      }
    else
      local all_names = { "fire_attack", "await_exhausted", }
      local names = U.getViewAsCardNames(player, "kl__duoshi", all_names, nil)
      if #names == 0 then return end
      return U.CardNameBox {
        choices = names,
        all_choices = all_names,
        -- default_choice = "kl__duoshi"
      }
    end
  end,
  -- card_filter = function(self, to_select, selected)
  --   return #selected == 0
  -- end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    -- if #cards ~= 1 or not self.interaction.data then return end
    -- local card = Fk:cloneCard(self.interaction.data)

    -- card.skillName = self.name
    -- if Fk:getCardById(cards[1]) then -- 检查 cards[1] 是否有效
    --   card:addSubcard(cards[1])
    -- else
    --   return
    -- end
    -- return card
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
  -- before_use = function(self, player, use)
  --   local room = player.room
  --   if not self.interaction.data then return end
  --   local card = Fk:cloneCard(self.interaction.data)
  --   if card.name == "fire_attack" and not player:isNude() then
  --     room:askForDiscard(player, 1, 1, true, self.name, false, ".", "#kl__duoshi-dis")
  --   elseif card.name == "await_exhausted" then
  --     player:drawCards(1, self.name)
  --   else
  --     return
  --   end
  -- end,
  -- after_use = function(self, player, use)
  --   if not player.dead and not use.damageDealt then
  --     player.room:invalidateSkill(player, self.name, "-phase")
  --   end
  -- end,
  -- enabled_at_play = Util.TrueFunc,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 2
  end,
}
luxun:addSkill(kl__qianxun)
luxun:addSkill(kl__duoshi)
Fk:loadTranslationTable {
  ["kl__luxun"] = "陆逊",
  ["#kl__luxun"] = "儒生雄才",
  ["designer:kl__luxun"] = "抗绿先锋",

  ["kl__qianxun"] = "谦逊",
  [":kl__qianxun"] = "锁定技，当你不因使用而失去牌后，若你的手牌数：不小于手牌上限，你的手牌上限+1；小于手牌上限，你摸一张牌并令你的手牌上限-1。",
  ["kl__duoshi"] = "度势",
  [":kl__duoshi"] = "出牌阶段限两次，你可视为使用【火攻】或【以逸待劳】。",
  ["#kl__duoshi"] = "你可视为使用【火攻】或【以逸待劳】。",
  ["#kl__duoshi-dis"] = "弃置一张牌以视为使用一张【火攻】",

  ["$kl__qianxun1"] = "儒生脱尘，不为贪逸淫乐之事。",
  ["$kl__qianxun2"] = "谦谦君子，不饮盗泉之水。",
  ["$kl__duoshi1"] = "以今日之大势，当行此计。",
  ["$kl__duoshi2"] = "国之大计，审势为先。",
  ["~kl__luxun"] = "我的未竟之业……",
}

-- local zhugeke = General(extension, "kl__zhugeke", "wu", 3)
-- local kl__aocai = fk.CreateViewAsSkill {
--   name = "kl__aocai",
--   pattern = ".|.|.|.|.|basic",
--   anim_type = "defensive",
--   prompt = "#kl__aocai",
--   card_filter = Util.FalseFunc,
--   interaction = function()
--     --FIXME: 不支持平辽（打出一张特定颜色的牌）、使用一张基本牌（因为不能正确地选择目标）的技能
--     --FIXME: 建议简化为只能使用【杀】、【闪】、【桃】、【酒】（管宁直呼内行）
--     --FIXME: 多牌名时会显示英文
--     --FIXME: 不支持鏖战（需要特判）
--     local names = U.getViewAsCardNames(Self, "kl__aocai", U.getAllCardNames("b", true))
--     return UI.ComboBox { choices = { table.concat(names, ",") } }
--   end,
--   view_as = function(self, cards)
--     if self.interaction.data == nil or self.interaction.data == "" then return end
--     local names = string.split(self.interaction.data, ",")
--     if #names > 0 then
--       local card = Fk:cloneCard(names[1])
--       card:setMark("kl__aocai_names", names)
--       return card
--     end
--   end,
--   before_use = function(self, player, use)
--     local room = player.room
--     local names = use.card:getMark("kl__aocai_names")
--     local cards = room:getNCards(3)
--     --FIXME: 需要判断合法性，但是没法区分是使用还是打出
--     local ids = table.filter(cards, function(id)
--       return table.contains(names, Fk:getCardById(id).trueName)
--     end)
--     cards = room:askForCard(player, 1, 1, false, self.name, true, tostring(Exppattern { id = ids }), "#kl__aocai-choose",
--       cards)
--     if #cards > 0 then
--       use.card = Fk:getCardById(cards[1])
--     else
--       return self.name
--     end
--   end,
--   enabled_at_play = Util.FalseFunc,
--   enabled_at_response = function(self, player, response)
--     return player.phase == Player.NotActive
--   end,
-- }
-- -- local kl__duwu = fk.CreateActiveSkill {
-- --   name = "kl__duwu",
-- --   anim_type = "offensive",
-- --   pattern = "slash",
-- --   prompt = "#kl__duwu",
-- --   can_use = Util.TrueFunc,
-- --   min_card_num = 1,
-- --   card_filter = function(self, to_select)
-- --     return true
-- --   end,
-- --   target_filter = function(self, to_select, selected, selected_cards, _, _, player)
-- --     if #selected < #selected_cards then
-- --       local card = Fk:cloneCard("slash")
-- --       card:addSubcards(selected_cards)
-- --       card.skillName = self.name
-- --       return card.skill:canUse(player, card) and card.skill:modTargetFilter(to_select, selected, player, card) and
-- --           not player:prohibitUse(card) and not player:isProhibited(Fk:currentRoom():getPlayerById(to_select), card)
-- --     end
-- --   end,
-- --   on_use = function(self, room, effect)
-- --     local player = room:getPlayerById(effect.from)
-- --     room:sortPlayersByAction(effect.tos)
-- --     room:useVirtualCard("slash", effect.cards, player, table.map(effect.tos, Util.Id2PlayerMapper), self
-- --       .name, true)
-- --     local use = room.logic:getCurrentEvent()
-- --     for _, pid in ipairs(TargetGroup:getRealTargets { effect.tos }) do
-- --       local times = #room.logic:getActualDamageEvents(1, function(e)
-- --         local u = e:findParent(GameEvent.UseCard, false, 3)
-- --         return u ~= nil and u.id == use.id and e.data[1].to.id == pid
-- --       end, Player.HistoryPhase, use.id)
-- --       if times == 0 then
-- --         room:sendLog { type = "#ceshi" }
-- --         room:drawCards(player, 1, self.name)
-- --         room:invalidateSkill(player, self.name, "-phase")
-- --         room:sendLog { type = "#ceshi" }
-- --       end
-- --     end
-- --   end
-- -- } --bug:for循环不对，times始终等于0
-- local kl__duwu = fk.CreateActiveSkill {
--   name = "kl__duwu",
--   anim_type = "offensive",
--   pattern = "slash",
--   prompt = "#kl__duwu",
--   card_filter = Util.FalseFunc,
--   target_filter = function(self, to_select, selected, selected_cards, _, _, player)
--     local handcards = player:getCardIds(Player.Hand)
--     if #selected < #handcards then
--       local card = Fk:cloneCard("slash")
--       -- card:addSubcards(handcards)
--       card.skillName = self.name
--       return card.skill:canUse(player, card) and card.skill:modTargetFilter(to_select, selected, player, card) and
--           not player:isProhibited(Fk:currentRoom():getPlayerById(to_select), card)
--     end
--   end,
--   can_use = function(self, player)
--     return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
--         and not player:prohibitUse(Fk:cloneCard("slash"))
--   end,
--   on_use = function(self, room, effect)
--     local player = room:getPlayerById(effect.from)
--     room:sortPlayersByAction(effect.tos)
--     local handcards = player:getCardIds(Player.Hand)
--     local card = Fk:cloneCard("slash")
--     card.skillName = self.name
--     card:addSubcards(handcards)
--     room:useCard {
--       from = player.id,
--       tos = table.map(effect.tos, Util.Id2PlayerMapper),
--       card = card,
--       extraUse = true,
--     }
--     local n = 0
--     player.room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
--       local use = e.data[1]
--       if use.from == player.id and table.contains(use.card.skillNames, "kl__duwu") then
--         if use.damageDealt then
--           for _, p in ipairs(player.room:getAllPlayers()) do
--             if use.damageDealt[p.id] then
--               n = n + use.damageDealt[p.id]
--             end
--           end
--         end
--       end
--       return false
--     end, Player.HistoryPhase)
--     player:drawCards(n, self.name)
--   end
-- } --有bug
-- zhugeke:addSkill(kl__aocai)
-- zhugeke:addSkill(kl__duwu)
-- Fk:loadTranslationTable {
--   ["kl__zhugeke"] = "诸葛恪",
--   ["#kl__zhugeke"] = "兴家赤族",
--   ["designer:kl__zhugeke"] = "官方&抗绿先锋",

--   ["kl__aocai"] = "傲才",
--   [":kl__aocai"] = "当你于回合外需要使用或打出一张基本牌时，你可以观看牌堆顶的两张牌，若你观看的牌中有相同牌名的牌，你可以使用或打出之。",
--   ["kl__duwu"] = "黩武",
--   [":kl__duwu"] = "出牌阶段限一次，你可将将所有手牌当无限制的【杀】对至多等量名角色使用。此【杀】结算结束后，你摸x张牌（x为此杀造成的伤害数）。",

--   ["#kl__duwu"] = "选择至多X名角色，使用所有手牌当无限制的【杀】对其使用（X为你的手牌数）。",
--   ["#kl__aocai"] = "发动 傲才，观看牌堆顶的三张牌，并可使用或打出其中你需要的基本牌",
--   ["#kl__aocai-choose"] = "傲才：选择你需要使用或打出的基本牌",

--   ["$kl__aocai1"] = "哼，易如反掌。",
--   ["$kl__aocai2"] = "吾主圣明，泽披臣属。",
--   ["$kl__duwu1"] = "破曹大功，正在今朝！",
--   ["$kl__duwu2"] = "全力攻城！言退者，斩！",
--   ["~kl__zhugeke"] = "重权震主，是我疏忽了……",
-- }

-- local sunshangxiang = General(extension, "kl__sunshangxiang", "wu", 3, 3, General.Female)
-- local kl__xiaoji = fk.CreateTriggerSkill {
--   name = "kl__xiaoji",
--   anim_type = "drawcard",
--   events = { fk.AfterCardsMove },
--   can_trigger = function(self, event, target, player, data)
--     if not player:hasSkill(self) then return end
--     for _, move in ipairs(data) do
--       if move.from == player.id then
--         for _, info in ipairs(move.moveInfo) do
--           if info.fromArea == Card.PlayerEquip then
--             return true
--           end
--         end
--       end
--     end
--   end,
--   on_trigger = function(self, event, target, player, data)
--     local i = 0
--     for _, move in ipairs(data) do
--       if move.from == player.id then
--         for _, info in ipairs(move.moveInfo) do
--           if info.fromArea == Card.PlayerEquip then
--             i = i + 1
--           end
--         end
--       end
--     end
--     self.cancel_cost = false
--     for _ = 1, i do
--       if self.cancel_cost or not player:hasSkill(self) then break end
--       self:doCost(event, target, player, data)
--     end
--   end,
--   on_cost = function(self, event, target, player, data)
--     if player.room:askForSkillInvoke(player, self.name) then
--       return true
--     end
--     self.cancel_cost = true
--   end,
--   on_use = function(self, event, target, player, data)
--     player:drawCards(2, self.name)
--   end,
-- }
-- local kl__jieyin = fk.CreateActiveSkill {
--   name = "kl__jieyin",
--   prompt = "#kl__jieyin-active",
--   anim_type = "support",
--   max_phase_use_time = 1,
--   can_use = function(self, player)
--     return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
--   end,
--   card_filter = function(self, to_select, selected)
--     return #selected < 2 and --Fk:currentRoom():getCardArea(to_select) == Player.Hand and
--         not Self:prohibitDiscard(Fk:getCardById(to_select))
--   end,
--   target_filter = function(self, to_select, selected, _, _, _, player)
--     local target = Fk:currentRoom():getPlayerById(to_select)
--     return target:isMale() and #selected < 1 and to_select ~= player.id
--   end,
--   target_num = 1,
--   card_num = 2,
--   on_use = function(self, room, effect)
--     local from = room:getPlayerById(effect.from)
--     local target = room:getPlayerById(effect.tos[1])
--     local choices = { "draw1", "recover" }
--     room:throwCard(effect.cards, self.name, from, from)

--     if from:isAlive() and not from:isWounded() then
--       from:drawCards(1, self.name)
--     elseif from:isAlive() and from:isWounded() then
--       local choices = room:askForChoice(from, choices, self.name)
--       if choices == "draw1" then
--         from:drawCards(1, self.name)
--       else
--         room:recover({
--           who = from,
--           num = 1,
--           recoverBy = from,
--           skillName = self.name
--         })
--       end
--     end
--     if target:isAlive() and not target:isWounded() then
--       target:drawCards(1, self.name)
--     elseif target:isAlive() and target:isWounded() then
--       local choices = room:askForChoice(target, choices, self.name)
--       if choices == "draw1" then
--         target:drawCards(1, self.name)
--       else
--         room:recover({
--           who = target,
--           num = 1,
--           recoverBy = from,
--           skillName = self.name
--         })
--       end
--     end
--   end
-- }
-- sunshangxiang:addSkill(kl__xiaoji)
-- sunshangxiang:addSkill(kl__jieyin)
-- Fk:loadTranslationTable {
--   ["kl__sunshangxiang"] = "孙尚香",
--   ["#kl__sunshangxiang"] = "弓腰姬",
--   ["designer:kl__sunshangxiang"] = "官方&抗绿先锋",

--   ["kl__xiaoji"] = "枭姬",
--   [":kl__xiaoji"] = "当你失去一张装备区的装备牌后，你可摸两张牌。",
--   ["kl__jieyin"] = "结姻",
--   [":kl__jieyin"] = "出牌阶段限一次，你可弃置两张牌并选择一名其他男性角色，你与其各回复1点体力或摸一张牌。",
--   ["#kl__jieyin-active"] = "发动 结姻，弃置两张牌并选择一名其他男性角色，你与其各回复1点体力或摸一张牌",

--   ["$kl__xiaoji1"] = "哼！",
--   ["$kl__xiaoji2"] = "看我的厉害！",
--   ["$kl__jieyin1"] = "夫君，身体要紧。",
--   ["$kl__jieyin2"] = "他好，我也好。",
--   ["~kl__sunshangxiang"] = "哎呀，这次弓箭射歪了。",
-- }

local cenhun = General(extension, "kl__cenhun", "wu", 3)
local kl__jishe = fk.CreateActiveSkill {
  name = "kl__jishe",
  anim_type = "drawcard",
  card_num = 0,
  target_num = 0,
  prompt = "#kl__jishe",
  can_use = function(self, player)
    return player:getMaxCards() > 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:addPlayerMark(player, MarkEnum.MinusMaxCardsInTurn, 1)
    room:broadcastProperty(player, "MaxCards")
    player:drawCards(1, self.name)
  end,
}
local kl__suojiang = fk.CreateTriggerSkill {
  name = "kl__suojiang",
  anim_type = "control",
  events = { fk.EventPhaseStart },
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish and
        player:getHandcardNum() < player.hp
  end,
  on_use = function(self, event, target, player, data)
    player:setChainState(true)
  end,
}
-- local kl__suojiang__kc = fk.CreateTriggerSkill {
--   name = "#kl__suojiang__kc",
--   anim_type = "defensive",
--   main_skill = kl__jishe,
--   events = { fk.TargetConfirming },
--   frequency = Skill.Compulsory,
--   can_trigger = function(self, event, target, player, data)
--     if not player:hasSkill(self) then return false end
--     return target == player and (data.card.name == "slash" or data.card.name == "duel") and player.chained
--   end,
--   on_use = function(self, event, target, player, data)
--     AimGroup:cancelTarget(data, player.id)
--     return true
--   end
-- }
local kl__suojiang__kc = fk.CreateTriggerSkill {
  name = "#kl__suojiang__kc",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = { fk.DamageInflicted },
  can_trigger = function(self, _, target, player, data)
    return target == player and player:hasSkill(self) and data.damageType == fk.NormalDamage and player.chained
  end,
  on_use = Util.TrueFunc,
}
kl__suojiang:addRelatedSkill(kl__suojiang__kc)
cenhun:addSkill(kl__jishe)
cenhun:addSkill(kl__suojiang)
Fk:loadTranslationTable {
  ["kl__cenhun"] = "岑昏",
  ["#kl__cenhun"] = "伐梁倾瓴",
  ["designer:kl__cenhun"] = "官方&抗绿先锋",

  ["kl__jishe"] = "极奢",
  [":kl__jishe"] = "出牌阶段，你可令本回合手牌上限-1（至少为0），然后摸一张牌。",
  ["#kl__jishe"] = "极奢：本回合手牌上限-1，摸一张牌",
  ["kl__suojiang"] = "锁江",
  ["#kl__suojiang__kc"] = "锁江",
  [":kl__suojiang"] = "锁定技，结束阶段，若你的手牌数小于体力值，你横置；当你受到非属性伤害时，若你已横置，防止之。",

  ["$kl__jishe1"] = "孙吴正当盛世，兴些土木又何妨？",
  ["$kl__jishe2"] = "当再建新殿，扬我国威！",
  ["$kl__suojiang1"] = "用那剩下的铁石，正好做些工事。",
  ["$kl__suojiang2"] = "筑下这铁链，江东天险牢不可破！",
  ["~kl__cenhun"] = "我为主上出过力！！！呃啊！",
}

local xushi = General(extension, "kl__xushi", "wu", 3, 3, General.Female)
local kl__wengua = fk.CreateActiveSkill {
  name = "kl__wengua",
  anim_type = "support",
  attached_skill_name = "kl__wengua&",
  card_num = 1,
  target_num = 0,
  prompt = "#kl__wengua",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  interaction = function()
    return UI.ComboBox { choices = { "Top", "Bottom" } }
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local index = 1
    local fromPlace = "bottom"
    local id = effect.cards[1]
    player:showCards(id)
    if self.interaction.data == "Bottom" then
      index = -1
      fromPlace = "top"
    end
    room:moveCards({
      ids = effect.cards,
      from = player.id,
      toArea = Card.DrawPile,
      moveReason = fk.ReasonPut,
      skillName = self.name,
      drawPilePosition = index,
    })
    if not player.dead then
      room:drawCards(player, 1, self.name, fromPlace)
      room:drawCards(player, 1, self.name, fromPlace)
    end
  end,
}
local kl__wengua_active = fk.CreateActiveSkill {
  name = "kl__wengua&",
  anim_type = "support",
  card_num = 1,
  target_num = 1,
  prompt = "#kl__wengua&",
  can_use = function(self, player)
    local targetRecorded = player:getTableMark("kl__wengua_targets-phase")
    return table.find(Fk:currentRoom().alive_players, function(p)
      return p ~= player and p:hasSkill(kl__wengua, true) and not table.contains(targetRecorded, p.id)
    end)
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and Fk:currentRoom():getPlayerById(to_select):hasSkill(kl__wengua) and
        not table.contains(Self:getTableMark("kl__wengua_targets-phase"), to_select)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    target:broadcastSkillInvoke("kl__wengua")
    room:addTableMarkIfNeed(player, "kl__wengua_targets-phase", target.id)
    local id = effect.cards[1]

    player:showCards(id)

    local choices = { "Top", "Bottom", "Cancel" }
    local choice = room:askForChoice(target, choices, "kl__wengua",
      "#kl__wengua-choice::" .. player.id .. ":" .. Fk:getCardById(id):toLogString())
    if choice == "Cancel" then return end
    local index = 1
    if choice == "Bottom" then
      index = -1
    end
    room:moveCards({
      ids = effect.cards,
      from = player.id,
      toArea = Card.DrawPile,
      moveReason = fk.ReasonJustMove,
      skillName = "kl__wengua",
      drawPilePosition = index,
    })
    if choice == "Top" then
      if not player.dead then
        player:drawCards(1, "kl__wengua", "bottom")
      end
      if not target.dead then
        target:drawCards(1, "kl__wengua", "bottom")
      end
    else
      if not player.dead then
        player:drawCards(1, "kl__wengua")
      end
      if not target.dead then
        target:drawCards(1, "kl__wengua")
      end
    end
  end,
}
local kl__fuzhu = fk.CreateTriggerSkill {
  name = "kl__fuzhu",
  anim_type = "offensive",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and target.phase == Player.Finish and
        (target:isMale())
        and #player.room.draw_pile <= 10 * player.hp
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#kl__fuzhu-invoke::" .. target.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, { target.id })
    local n = 0
    repeat
      n = n + 1
      local no_slash = true
      local slash
      for i = #room.draw_pile, 1, -1 do
        slash = Fk:getCardById(room.draw_pile[i])
        if slash.trueName == "slash" and player:canUseTo(slash, target, { bypass_times = true, bypass_distances = true }) then
          no_slash = false
          room:useCard({
            from = player.id,
            tos = { { target.id } },
            card = slash,
            extraUse = true,
          })
          break
        end
      end
      if no_slash then break end
    until (n >= #room.players or player.dead or target.dead or #room.draw_pile > 10 * player.hp)
    room:shuffleDrawPile()
  end,
}
Fk:addSkill(kl__wengua_active)
xushi:addSkill(kl__wengua)
xushi:addSkill(kl__fuzhu)
Fk:loadTranslationTable {
  ["kl__xushi"] = "徐氏",
  ["#kl__xushi"] = "节义双全",
  ["designer:kl__xushi"] = "官方&抗绿先锋",

  ["kl__wengua"] = "问卦",
  [":kl__wengua"] = "每名角色的出牌阶段限一次，其可展示一张牌，你可将此牌置于牌堆一端，令其与你从另一端各摸一张牌。",
  ["kl__fuzhu"] = "伏诛",
  [":kl__fuzhu"] = "一名男性角色结束阶段，若牌堆剩余牌数不大于你体力值的十倍，你可以依次对其使用牌堆中所有的【杀】（不能超过游戏人数），然后洗牌。",
  ["#kl__wengua"] = "问卦：你可展示一张牌，将此牌置于牌堆顶或牌堆底，从另一端摸两张牌",
  ["#kl__wengua-choice"] = "问卦：你可将 %arg 置于牌堆顶或牌堆底，令 %dest 与你从另一端各摸一张牌",
  ["kl__wengua&"] = "问卦",
  [":kl__wengua&"] = "出牌阶段限一次，你可展示一张牌，然后徐氏可将此牌置于牌堆一端，令你与其从另一端各摸一张牌。",
  ["#kl__wengua&"] = "问卦：你可展示一张牌，然后徐氏可将此牌置于牌堆一端，令你与其从另一端各摸一张牌",
  ["#kl__fuzhu-invoke"] = "伏诛：你可对 %dest 使用牌堆中所有【杀】！",

  ["$kl__wengua1"] = "阴阳相生相克，万事周而复始。",
  ["$kl__wengua2"] = "卦不能佳，可须异日。",
  ["$kl__fuzhu1"] = "我连做梦都在等这一天呢。",
  ["$kl__fuzhu2"] = "既然来了，就别想走了。",
  ["~kl__xushi"] = "莫问前程凶吉，但求落幕无悔。",
}

local quancong = General(extension, "kl__quancong", "wu", 4, 4, General.Male)
local kl__zhenshan = fk.CreateViewAsSkill {
  name = "kl__zhenshan",
  pattern = ".|.|.|.|.|basic",
  interaction = function(self)
    local all_names = U.getAllCardNames("b")
    local names = U.getViewAsCardNames(Self, self.name, all_names)
    if #names == 0 then return end
    return U.CardNameBox { choices = names, all_names = all_names }
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p)
      return (#p.player_cards[Player.Hand] < player:getHandcardNum())
    end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "#kl__zhenshan-choose", self.name, false)
    if #tos < 1 then return "" end
    local to = room:getPlayerById(tos[1])
    U.swapHandCards(room, player, player, to, self.name)
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and
        table.find(Fk:currentRoom().alive_players, function(p) return p:getHandcardNum() < player:getHandcardNum() end)
  end,
  enabled_at_response = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and
        table.find(Fk:currentRoom().alive_players, function(p) return p:getHandcardNum() < player:getHandcardNum() end)
  end,
}
quancong:addSkill(kl__zhenshan)
Fk:loadTranslationTable {
  ["kl__quancong"] = "全琮",
  ["#kl__quancong"] = "慕势耀族",
  ["designer:kl__quancong"] = "凌风自舞",

  ["kl__zhenshan"] = "振赡",
  [":kl__zhenshan"] = "每回合限一次，当你需要使用或打出一张基本牌时，你可以与一名手牌数少于你的角色交换手牌，若如此做，视为你使用或打出此牌。",
  ["#kl__zhenshan-choose"] = "振赡：与一名手牌数少于你的角色交换手牌",

  ["$kl__zhenshan1"] = "看我如何以无用之力换己所需，哈哈哈！",
  ["$kl__zhenshan2"] = "民不足食，何以养军？",
  ["~kl__quancong"] = "儿啊，好好报答吴王知遇之恩……",
}
return extension
